package com.blackfish.common.plugin;

import java.util.HashMap;
import java.util.Map;

public class ClientHelper {
    private static volatile  ClientHelper clientHelper;
    private static Map<String,TioLoopClient> cliMap = new HashMap<String,TioLoopClient>();

    public ClientHelper(){
        System.out.println("create " + getClass().getSimpleName());
    }

    public static ClientHelper getInstance(){
        synchronized (ClientHelper.class) {
            if (clientHelper == null) {
                clientHelper = new ClientHelper();
            }
        }
        return clientHelper;
    }

    public static boolean haveImInClimap(String ip){
        if(cliMap.get(ip)!=null){
            return true;
        }
        return false;
    }

    public static boolean addImConnection(String ip,int port) throws Exception {
        if(!haveImInClimap(ip)){
            TioLoopClient tioLoopClient = new TioLoopClient();
            if(tioLoopClient.start(ip,port)==true){
                cliMap.put(ip,tioLoopClient);
                tioLoopClient.send("login","main","root");
                return true;
            }
            return false;
        }
        return true;
    }

    public static boolean sendImMessage(String deviceId,String content,String ip) throws Exception {
        TioLoopClient tioLoopClient = cliMap.get(ip);
        return tioLoopClient.send("p2pMsg",deviceId,content);
    }

}
